package org.lee.img;

import javax.swing.*;
import java.awt.*;

/**
 * CustomIconDemo
 * 自定义
 *
 * @author dralee
 * @date 2021-12-29 16:23:51
 **/
public class CustomIconDemo extends JFrame {

    public CustomIconDemo() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        JLabel lbl = new CustLabel(new MissingIcon());
        lbl.setBackground(Color.gray);
        add(lbl);
        
        setSize(250, 150);
        setTitle("Custom icon");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    class CustLabel extends JLabel {
        public CustLabel(Icon icon) {
            super(icon);
        }

        @Override
        public boolean isOpaque() {
            return true;
        }
    }

    class MissingIcon implements Icon {

        private final int WIDTH = 32;
        private final int HEIGHT = 32;
        private final BasicStroke stroke = new BasicStroke(5);

        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            doDrawing(g, x, y);
        }

        private void doDrawing(Graphics g, int x, int y) {
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.white);
            g2d.fillRect(x + 1, y + 1, WIDTH - 2, HEIGHT - 2);

            g2d.setColor(Color.darkGray);
            g2d.drawRect(x + 1, y + 1, WIDTH - 2, HEIGHT - 2);

            g2d.setColor(Color.red);
            g2d.setStroke(stroke);
            g2d.drawLine(x + 10, y + 10, x + WIDTH - 10, y + HEIGHT - 10);
            g2d.drawLine(x + 10, y + HEIGHT - 10, x + WIDTH - 10, y + 10);

            g2d.dispose();
        }

        @Override
        public int getIconWidth() {
            return WIDTH;
        }

        @Override
        public int getIconHeight() {
            return HEIGHT;
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new CustomIconDemo().setVisible(true));
    }
}
